from datetime import datetime
from rest_framework.generics import ListAPIView, GenericAPIView,RetrieveAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from apps.activity.models import Gathering
from apps.activity.serializers import GatheringsSerializer, GatheringDetailsSerializer
from rest_framework.permissions import IsAuthenticated

from rest_framework.pagination import PageNumberPagination

# 重写分页
class PageNum(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'page_size'
# 活动列表视图
class GatheringsListView(ListAPIView):

    queryset = Gathering.objects.all()
    serializer_class = GatheringsSerializer
    pagination_class = PageNum

# 活动详情视图
# class GatheringDetailsView(APIView):
class GatheringDetailsView(RetrieveAPIView):

    # def get(self,request,pk):
    #     gathering = Gathering.objects.filter(id=pk)
    #     serializer = GatheringDetailsSerializer(gathering,many=True)
    #     return Response(serializer.data)
    serializer_class = GatheringDetailsSerializer
    queryset = Gathering.objects.all()

# 报名活动视图
class GatheringsJoinView(GenericAPIView):

    queryset = Gathering.objects.filter(state=1)
    # serializer_class = GatheringDetailsSerializer
    # 设置登录用户才可以访问
    permission_classes = [IsAuthenticated]

    def get(self,request,pk):
        # 根据id查询数据有则继续操作，没有则返回404
        # try:
        #     object = Gathering.objects.get(id=id)
        # except Exception:
        #     return Response(status=status.HTTP_404_NOT_FOUND)
        user = request.user
        gathering = self.get_object()
        # 用现在的时间和活动结束时间比较在活动内则可以报名，否则不能报名
        nowtime = datetime.now()
        endtime = gathering.endrolltime.replace(tzinfo=None)
        if endtime < nowtime:
            return Response({'message':'报名时间已过','success':False},status=400)
        else:
            if user in gathering.users.all():
                gathering.users.remove(user)
                gathering.save()
                return Response({'success': True, 'message': '取消成功'})
            else:
                gathering.users.add(user)
                gathering.save()
                return Response({'success': True, 'message': '参加成功'})
